<template>
  <div>
    <!-- 拖拽开关 -->
    <el-switch 
    v-model="draggable" 
    active-text="开启拖拽" 
    inactive-text="关闭拖拽">
    </el-switch>

    <el-button @click="batchDelete" type="danger">批量删除</el-button>

    <el-button v-if="draggable" type="primary" @click="updateSort">更新排序数据</el-button>

    <!-- 三级类目 -->
    <el-tree
      :data="data"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandKeys"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="tree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <!-- 添加 -->
          <el-button
            v-if="data.catLevel <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            添加
          </el-button>
          <!-- 修改 -->
          <el-button type="text" size="mini" @click="() => edit(data)">
            修改
          </el-button>
          <!-- 删除 -->
          <el-button
            v-if="data.childrens.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            删除
          </el-button>
        </span>
      </span>
    </el-tree>

    <!-- 添加-修改-弹框 -->
    <el-dialog
      :title="addCategoryTyoe == 1 ? '新增类目' : '修改类目'"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="categoryForm">
        <el-form-item label="类别名称:">
          <el-input v-model="categoryForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标:">
          <el-input v-model="categoryForm.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位:">
          <el-input
            v-model="categoryForm.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
import { treeDataTranslate } from "../../../utils";

export default {
  data() {
    return {
      pCids:[],   //拖拽后的父节点数组
      updateNodes: [], //拖拽节点后需要更新的数据
      maxLevel: 0,
      addCategoryTyoe: 1, //1=代表新增   2=代表修改
      data: [],
      draggable:false,  //默认拖拽功能关闭
      expandKeys: [],
      dialogVisible: false, //弹框默认为false关闭
      categoryForm: {
        name: null,
        icon: null,
        productUnit: null,
        showStatus: 1,
        sort: 0,
        catId: null,
        catLevel: 1,
      }, //表单数据
      defaultProps: {
        children: "childrens",
        label: "name",
      },
    };
  },
  methods: {
    //批量删除按钮
    batchDelete(){
        let catIds = [];
        let checkNodes = this.$refs.tree.getCheckedNodes(false,false);
        //循环遍历把catId赋值catIds
        for (let i = 0; i < checkNodes.length; i++) {
            catIds.push(checkNodes[i].catId);
        }
        this.$confirm(`此操作将【${catIds}】的数据删除, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl(`/product/category/delete`),
            method: "post",
            data: this.$http.adornData(catIds, false),
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              //重新加载菜单数据
              this.getCategory();
              //设置默认展开父节点信息
              this.expandKeys = [node.parent.data.catId];
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //拖拽时触发
    handleDrop(draggingNode, dropNode, type, event) {
      //1.拖拽系欸但的父节点需要修改
      let parentId = 0;
      let siblings = null;
      //如果拖拽至里面
      if (type == "inner") {
        parentId = dropNode.data.catId;
        siblings = dropNode.childNodes;
      } else {
        parentId =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      }
      //2.拖拽后节点所在的新的兄弟节点的排序问题
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          //3.拖拽后的节点及节点的catLevel更新问题
          let catLevel = draggingNode.level;
          //如果是平行移动
          if (siblings[i].level != catLevel) {
            catLevel = siblings[i].level;
            //递归更新子节点层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: parentId,
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
      // this.updateSort(parentId);
      this.pCids.push(parentId);
    },

    //批量更新拖拽后的顺序
    updateSort() {
      console.log("aaaaaa->", this.updateNodes);
      this.$http({
        url: this.$http.adornUrl(`/product/category/BatchUpdate`),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        if (data && data.code === 200) {
          this.$message({
            message: "数据拖拽成功",
            type: "success",
          });
          //关闭弹框
          (this.dialogVisible = false),
            //重新加载菜单数据
            this.getCategory();
          //设置默认展开父节点信息
          this.expandKeys = this.pCids;
          //重置存储拖拽数据的容器
          this.updateNodes = [];
          this.maxLevel = 0;
        } else {
          this.$message.error(data.msg);
        }
      });
    },

    //更新拖拽后的数据
    updateChildNodeLevel(node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var childNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: childNodes.catId,
            catLevel: node.childNodes[i].level,
          });
          //如果还有子节点，同步的更新处理
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },

    // 判断拖拽的节点是否可移动至目标节点
    allowDrop(draggingNode, dropNode, type) {
      //获取当前被拖拽的节点最大的level
      this.countNodeLevle(draggingNode);
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
      if (type == "inner") {
        return deep + dropNode.level <= 3;
      }
      return deep + dropNode.parent.level <= 3;
    },
    //获取当前被拖拽的节点最大的level
    countNodeLevle(node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevle(node.childNodes[i]);
        }
      } else {
        this.maxLevel = node.level;
      }
    },

    //查询类目数据
    getCategory() {
      this.$http({
        url: this.$http.adornUrl("/product/category/listTree"),
        method: "get",
      }).then(({ data }) => {
        console.log("成功获取类目数据:" + data.data);
        this.data = data.data;
      });
    },

    //打开添加弹框
    append(data) {
      this.dialogVisible = true;
      //赋默认值
      this.categoryForm.parentCid = data.catId;
      this.categoryForm.catLevel = data.catLevel + 1;
      this.categoryForm.showStatus = 1;
      this.categoryForm.sort = 0;
      // 重置更新数据
      (this.categoryForm.name = null),
        (this.categoryForm.catId = ""),
        (this.categoryForm.icon = ""),
        (this.categoryForm.productUnit = ""),
        (this.addCategoryTyoe = 1);
    },

    //弹框确定按钮
    submitForm() {
      if (this.addCategoryTyoe == 1) {
        this.addCategory();
      } else {
        this.editDialog();
      }
    },

    //添加方法
    addCategory() {
      this.$http({
        url: this.$http.adornUrl(`/product/category/save`),
        method: "post",
        data: this.$http.adornData(this.categoryForm, false),
      }).then(({ data }) => {
        if (data && data.code === 200) {
          this.$message({
            message: "添加成功",
            type: "success",
          });
          //关闭弹框
          (this.dialogVisible = false),
            //重新加载菜单数据
            this.getCategory();
          //设置默认展开父节点信息
          this.expandKeys = [this.categoryForm.parentCid];
        } else {
          this.$message.error(data.msg);
        }
      });
    },

    //打开修改弹框
    edit(data) {
      this.addCategoryTyoe = 2;

      //根据ID获取最新数据回显
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "post",
        data: this.$http.adornData(this.categoryForm.catId, false),
      }).then(({ data }) => {
        //表单数据回显
        this.categoryForm.name = data.category.name;
        this.categoryForm.productUnit = data.category.productUnit;
        this.categoryForm.icon = data.category.icon;
        this.categoryForm.catId = data.category.catId;
        this.categoryForm.catLevel = data.category.catLevel;
        this.categoryForm.showStatus = 1;
        this.categoryForm.sort = 0;
        this.categoryForm.parentCid = data.category.parentCid;

        //打开弹框
        this.dialogVisible = true;
      });
    },

    //修改方法
    editDialog() {
      this.$http({
        url: this.$http.adornUrl(`/product/category/update`),
        method: "post",
        data: this.$http.adornData(this.categoryForm, false),
      }).then(({ data }) => {
        if (data && data.code === 200) {
          this.$message({
            message: "更新成功",
            type: "success",
          });
          //关闭弹框
          (this.dialogVisible = false),
            //重新加载菜单数据
            this.getCategory();
          //设置默认展开父节点信息
          this.expandKeys = [this.categoryForm.parentCid];
        } else {
          this.$message.error(data.msg);
        }
      });
    },

    //删除方法
    remove(node, data) {
      this.$confirm(`此操作将【${data.name}】的数据删除, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //传递数据
          let ids = [data.catId];
          this.$http({
            url: this.$http.adornUrl(`/product/category/delete`),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              //重新加载菜单数据
              this.getCategory();
              //设置默认展开父节点信息
              this.expandKeys = [node.parent.data.catId];
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },

  created() {
    this.getCategory();
  },
};
</script>

<style>
</style>